package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.HttpStatus;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit
    private String tradeNo(Long userId) {
        String tradeKey = "user:trade:" + userId;
        String tradeNo = UUID.randomUUID().toString().replace("-", "");

        //将交易流水号保存至Redis缓存
        redisTemplate.opsForValue().set(tradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {
        //获取用户ID
        Long userId = SecurityContextHolder.getUserId();
        //获取购物车商品数据信息
        R<List<CartInfo>> cartCheckedListFromRedis = remoteCartService.getCartCheckedList(userId,SecurityConstants.INNER);
        if (cartCheckedListFromRedis.getCode() == HttpStatus.ERROR) {
            throw new ServiceException(cartCheckedListFromRedis.getMsg());
        }
        List<CartInfo> cartCheckedList = cartCheckedListFromRedis.getData();
        if (cartCheckedList == null) {
            throw new ServiceException("已添加订单的商品为空");
        }
        //封装商品信息至订单信息
        List<OrderItem> orderItemList = cartCheckedList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).toList();
        //计算订单交易金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        //完善补充订单信息
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo(userId));

        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        //获取用户信息userId
        Long userId = SecurityContextHolder.getUserId();
        //1 通过删除流水号数据判断用户是否重复提交订单
        String tradeNo = orderForm.getTradeNo();
        String tradeKey = "user:trade:" + userId;

        String script = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                "then \n" +
                "\treturn redis.call('del',KEYS[1])\n" +
                "else\n" +
                "\treturn 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeKey), tradeNo);
        if (result == 0) {
            throw new ServiceException("您不能重复提交订单");
        }
        //2 校验订单参数是否合法(提交订单是否为空)
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("订单商品列表为空");
        }
        //3 校验商品价格变动,如有更新,提交失败,需重新下单
        //获取商品skuId
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        //查询商品价格
        R<List<SkuPrice>> skuPriceListFromDB = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (skuPriceListFromDB.getCode() == HttpStatus.ERROR){
            throw new ServiceException(skuPriceListFromDB.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListFromDB.getData();
        Map<Long, BigDecimal> skuIdToPriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        //价格对比
        StringBuilder builder = new StringBuilder("");
        for (OrderItem orderItem : orderItemList) {
            BigDecimal salePriceDB = skuIdToPriceMap.get(orderItem.getSkuId());
            if(orderItem.getSkuPrice().compareTo(salePriceDB) != 0){
                builder.append(orderItem.getSkuName()).append("价格变了;"); //  xxx价格变了;yyy价格变了;
            }
        }

        if(StringUtils.hasText(builder.toString())){
            //修改购物车价格,并抛出异常,终止下单
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw new ServiceException(builder.toString());
        }
        //4 确认价格,锁定库存数据
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map((orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            //skuLockVo.setIsHaveStock(false); //默认false
            return skuLockVo;
        })).toList();

        R<String> stringR = remoteProductService.checkAndLock(tradeNo, skuLockVoList, SecurityConstants.INNER);
        if(stringR.getCode()==HttpStatus.ERROR){
            throw new ServiceException(stringR.getMsg());
        }

        //5 保存订单信息(订单表,订单项表,订单日志表)
        Long orderId = null;
        try {
            //返回订单ID
            orderId = saveOrder(orderForm);
        } catch (Exception e) {
            //异常原因下单失败 解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }
        //6.删除购物车选中商品
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);

        return orderId;
    }


    @Transactional
    //辅助方法： 保存订单数据(订单表、订单项表、订单日志表)
    public Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        //1.保存订单对象
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo()); //交易流水号作为订单号。
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName); //用登录账号作为昵称。否则，需要远程调用接口获取昵称数据；
        orderInfo.setRemark(orderForm.getRemark()); //备注
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); //实付总价格  减掉优惠卷 + 运费    之后的钱
        orderInfo.setCouponAmount(new BigDecimal(0)); //优惠卷钱    暂时业务取消
        orderInfo.setOriginalTotalAmount(totalAmount); // 商品总价格  只包含商品的钱。不包含优惠卷、运费
        orderInfo.setFeightFee(orderForm.getFeightFee()); //运费   免运费
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderInfoMapper.insert(orderInfo); //主键回填


        //2.保存多个订单项
        //orderItemList = orderForm.getOrderItemList();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId()); //FK
            orderItemMapper.insert(orderItem);
        }

        //3.保存订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }

}